<template>
    <div class="login">
        <div class="from">
            <div class="errfrom" v-show="isErr">
                <div>
                    <i class="el-icon-error"></i>
                    <span class="errMsg">{{ errMsg }}</span>
                </div>
                <div>
                    <i class="el-icon-close close" @click="closeErrMsg"></i>
                </div>
            </div>
            <!-- 密码登录 -->
            <div>
                <div class="form-item">
                    <input
                        type="text"
                        name="username"
                        placeholder="账户"
                        v-model="passwordLogin.number"
                    />
                </div>
                <div class="form-item">
                    <input
                        type="password"
                        name="password"
                        placeholder="密码"
                        v-model="passwordLogin.password"
                    />
                </div>
                <div class="phone-login-row">
                    <div class="form-item-phone">
                        <input
                            type="text"
                            name="password"
                            placeholder="输入验证码"
                            v-model="passwordLogin.code"
                        />
                    </div>
                    <!-- 动态验证码 -->
                    <canvas
                        class="imgCode"
                        ref="canvas"
                        @click="get_vis_code"
                    ></canvas>
                </div>
            </div>

            <div class="meun">
                <el-checkbox
                    label="自动登录"
                    v-model="isAutomaticLogin"
                ></el-checkbox>
            </div>
            <div class="loginBtn" @click="login">
                登录
            </div>
            <div class="otherLogin">
                <div
                    class="greenTextBtn"
                    @click="checkPageType('ForgetPawPage')"
                >
                    忘记密码
                </div>
                <div class="greenTextBtn" @click="checkPageType('Register')">
                    注册账户
                </div>
            </div>
        </div>
    </div>
</template>

<script>
import { Base64 } from "js-base64";
import CryptoJS from "crypto-js";
import { draw } from "@/utils/Verification";
import { set_localStorage, set_sessionStorage } from "@/utils/localToken";

import { getVisCode, getToken, getUserInfo } from "@/api/login"; //getAccount

export default {
    data() {
        return {
            isErr: false, //账户密码错误
            errMsg: "错误消息", //错误消息
            Verification_key: "",
            passwordLogin: {
                //密码登录
                number: "",
                password: "",
                code: ""
            },
            isAutomaticLogin: false, //是否自动登录
            loading: null //加载组件
        };
    },
    async created() {
        this.get_vis_code();
    },
    mounted() {
        //绑定事件
        window.addEventListener("keydown", this.keyDown);
    },
    destroyed() {
        window.removeEventListener("keydown", this.keyDown, false);
    },
    methods: {
        keyDown(e) {
            //如果是回车则执行登录方法
            if (e.keyCode == 13) {
                this.login();
            }
        },
        checkPageType(type) {
            this.$emit("checkPageType", type);
        },
        closeErrMsg() {
            this.isErr = false;
        },
        //获取限制验证码
        async get_vis_code() {
            var visData = await getVisCode();
            this.Verification_key = visData.data.Verification_key;
            var str = visData.data.Verification_val.toString();
            draw(str.split(""), this.$refs.canvas);
        },
        getDES(password) {
            //加密
            var key = "97498121231284655fsafasa"; //密钥
            var iv = "kfao5417";
            var encrypted = this.getDesString(password, key, iv); //密文
            return Base64.encode(encrypted);
        },
        getDesString(data, key, iv) {
            //加密
            var C_key = CryptoJS.enc.Utf8.parse(key);
            var C_iv = CryptoJS.enc.Utf8.parse(iv);
            var encrypted = CryptoJS.DES.encrypt(data, C_key, {
                iv: C_iv, //向量  偏移量
                mode: CryptoJS.mode.CBC, //加密模式
                padding: CryptoJS.pad.Pkcs7 //填充模式 补位
            });
            return encrypted.toString(); //返回的是base64格式密文
        },
        // 登录
        async login() {
            if (
                this.passwordLogin.number.trim() == "" ||
                this.passwordLogin.password.trim() == ""
            ) {
                this.errMsg = "账户或密码不能为空";
                this.isErr = true;
                return;
            } else if (this.passwordLogin.code.trim() == "") {
                this.errMsg = "请输入验证码";
                this.isErr = true;

                return;
            } else {
                this.isErr = false;
                var _this = this;
                //密码加密
                var password = _this.getDES(_this.passwordLogin.password);
                let reqObj = {
                    phone: _this.passwordLogin.number,
                    pwd: password,
                    login_type: 1,
                    Verification_key: this.Verification_key,
                    Verification_val: _this.passwordLogin.code
                };
                _this.loading = this.$loading({
                    lock: true,
                    text: "Loading",
                    spinner: "el-icon-loading",
                    background: "rgba(0, 0, 0, 0.7)"
                });
                var loginData = await getToken(reqObj);

                if (loginData.code === 200) {
                    console.log("====================================");
                    console.log("获取TOKEN", loginData.data);
                    console.log("====================================");
                    var token = loginData.data.k_token;
                    this.$store.commit("user/SETTING_K_TOKEN", token);
                    //保存会话
                    set_localStorage("phone", this.passwordLogin.number);
                    set_sessionStorage("k_token", token);
                    // 是否自动登录
                    if (_this.isAutomaticLogin) {
                        console.log("选择自动登录");
                        set_localStorage("k_token", token);
                    }
                    var infoData = await getUserInfo({
                        k_token: token
                    });
                    console.log("====================================");
                    console.log("用户信息", infoData);
                    console.log("====================================");
                    if (infoData.code == 200) {
                        this.$store.commit(
                            "user/SETTING_USERINFO",
                            infoData.data
                        );
                        if (infoData.data.school == null) {
                            this.$router.push("/perfect");
                        } else {
                            this.$router.push("/home");
                        }
                    } else {
                        this.$confirm("登录失败", "提示", {
                            confirmButtonText: "确定",
                            type: "warning"
                        });
                    }
                    // var userInfoData = await getAccount({
                    //     k_token: token
                    // });
                    // console.log("====================================");
                    // console.log("获取a_token账号信息", userInfoData);
                    // console.log("====================================");
                    // if (userInfoData.code == 0) {
                    //     this.$store.commit(
                    //         "user/SETTING_A_TOKENINFO",
                    //         userInfoData.data
                    //     );
                    //     // set_sessionStorage("a_token", userInfoData.data.a_token);
                    //     // set_localStorage("a_token", userInfoData.data.a_token);
                    //     var infoData = await getUserInfo({
                    //         k_token: token
                    //     });
                    //     console.log("====================================");
                    //     console.log("用户信息", infoData);
                    //     console.log("====================================");
                    //     if (infoData.code == 200) {
                    //         this.$store.commit(
                    //             "user/SETTING_USERINFO",
                    //             infoData.data
                    //         );
                    //         this.$router.push("/home");
                    //     } else {
                    //         this.$confirm("登录失败", "提示", {
                    //             confirmButtonText: "确定",
                    //             type: "warning"
                    //         });
                    //     }
                    // } else {
                    //     this.$confirm("登录失败", "提示", {
                    //         confirmButtonText: "确定",
                    //         type: "warning"
                    //     });
                    // }
                    this.loading.close();
                } else {
                    this.loading.close();
                    this.$alert(loginData.msg, "提示", {
                        confirmButtonText: "确定",
                        callback: () => {}
                    });
                    this.get_vis_code();
                }
            }
        }
    }
};
</script>

<style scoped lang="scss">
@import "./mixin.css";

.imgCode {
    height: 40px;
    width: 150px;
    margin-left: 10px;
    border: 1px solid #e5e5e5;
    cursor: pointer;
}

/* 登录 */
.login {
    width: 400px;
    margin: 0 auto;
    margin-top: 62px;
    position: relative;

    .meun {
        width: 100%;
        display: flex;
        justify-content: space-between;
        font-size: 14px;
        height: 22px;
        line-height: 22px;
        margin-bottom: 24px;
    }

    .loginBtn {
        width: 100%;
        height: 40px;
        text-align: center;
        font-size: 16px;
        color: #ffffff;
        line-height: 40px;
        background: #9ea4b0;
        opacity: 1;
        border-radius: 20px;
        cursor: pointer;
        margin-bottom: 24px;

        &:hover {
            opacity: 0.8;
        }
    }

    .otherLogin {
        display: flex;
        justify-content: space-between;
        font-size: 14px;
        color: #6d7785;
        height: 24px;
        line-height: 24px;
    }
}
</style>
